<?php
namespace app\task\model;

use app\common\model\Order as OrderModel;
use app\common\model\User as UserModel;
use app\common\model\Goods as GoodsModel;
use app\common\model\Device;
use think\facade\Cache;
use think\facade\Db;

/**
 * 订单模型
 */
class Order extends OrderModel
{
    /**
     * 待支付订单详情
     */
    public function payDetail($order_no)
    {
        return self::with(['goods','shop','table','address'])->where(['order_no' => $order_no, 'pay_status' => 10])->find();
    }

    /**
     * 更新付款状态
     */
    public function updatePayStatus($transaction_id)
    {
		
		if($this['pay_status']['value']==20){
			//避免重复回调
			return true;
		}
		
        // 开启事务
        Db::startTrans();
        try {
        	
			// 更新商品库存、销量
			$GoodsModel = new Goods;
			$GoodsModel->updateStockSales($this->goods);
			
			//更新用户信息
			$user = UserModel::get($this->user_id);
			$user->pay = ['inc', $this->pay_price];//增加消费金额
			$user->score = ['inc', $this->pay_price];//增加积分
			$user->save();
			// 更新订单状态
			$this->save([
				'pay_status' => 20,
				'pay_time' => time(),
				'transaction_id' => $transaction_id,
			]);
			//发送新订单提醒，管理员,店长
			sand_new_order_msg($this);
			Device::print($this);//打印订单
			Device::push($this->shop_id,'pay',$this->pay_price);//收款提醒
			//商家是否自动接单
			if($this['shop']['is_order']['value'] == 1){
				$this->setShopStatus();
				//外卖自动推送订单
				if($this['order_mode']['value']==20 AND $this['shop']['is_delivery']['value'] == 1){
					$this->setDelivery($this['shop']['delivery_id']);
				}
			}
			Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }

	/**
     * 待退款订单详情
     */
    public function refundDetail($order_no)
    {
		return self::get(['order_no' => $order_no, 'order_status' => 40, 'refund_status' => 10], ['goods']);
    }
	
	/**
     * 更新退款款状态
     */
    public function updateRefundStatus($refund_id)
    {
		if(!empty($this->refund_id)){
			//避免重复回调
			return true;
		}
        // 开启事务
        Db::startTrans();
        try {
			//更新商品库存、销量
			//$GoodsModel = new Goods;
			//$GoodsModel->updateStockSales($this['goods']);
			//更新用户信息
			$user = UserModel::get($this->user_id);
			$user->pay = ['dec', $this->refund_price];//扣减消费金额
			$user->score = ['dec', $this->refund_price];//扣减积分
			$user->save();
			// 更新订单状态
			$this->save([
				'refund_status' => 20,
				'refund_time' => time(),
				'refund_id' => $refund_id,
			]);
			//发送退款申请状态提醒订阅消息
			food_post_tpl('refund',$this->order_id);
			Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }
	
    
	
	/**
     * 更新第三方配送状态
	 * $mode 配送模式 20=顺丰 30=达达 40=UU
     */
    public function updateDeliveryStatus($data,$mode)
    {
		$data = [];
		if($mode==1){
			//订单状态回调
			if($order['url_index']=='rider_status'){
				//配送员已结单
				if($order['order_status']==10){
					$data['transport_status'] = '已抢单';
					$data['receipt_status'] = 20;
					$data['receipt_time'] = time();
					$data['delivery_name'] = $order['operator_name'];
					$data['delivery_mobile'] = $order['operator_phone'];
				}
				//配送员到店
				if($order['order_status']==12){
					$data['transport_status'] = '已到店';
				}
				//配送员配送中
				if($order['order_status']==15){
					$data['transport_status'] = '配送中';
				}
			}
			//订单完成回调
			if($order['url_index']=='order_complete'){
				//配送已完成
				if($order['order_status']==17){
					$data['transport_status'] = '已收货';
					$data['receipt_status'] = 30;
					$data['receipt_time'] = time();
				}
			}
			//订单取消回调
			if($order['url_index']=='sf_cancel'){
				//顺丰原因取消
				if($order['order_status']==2){
					$data['transport_status'] = '已取消';
					$data['receipt_status'] = 10;
					$data['receipt_time'] = 0;
					$data['delivery_status'] = 10;//退回已结单待烹制完成阶段
					$data['delivery_time'] = 0;
				}
			}
		}
		if($mode==2){
			$data['receipt_time'] = time();
			if($order['order_status'] == 2){
				$data['receipt_status'] = 20;
				$data['transport_status'] = '已抢单';
				$data['delivery_name'] = $order['dm_name'];
				$data['delivery_mobile'] = $order['dm_mobile'];
			}
			if($order['order_status'] == 3){
				$data['transport_status'] = '配送中';
			}
			if($order['order_status'] == 4){
				$data['transport_status'] = '已完成';
				$data['receipt_status'] = 30;
			}
			if($order['order_status'] == 5){
				$data['transport_status'] = '已取消';
				$data['receipt_status'] = 10;
				$data['receipt_time'] = 0;
				$data['delivery_status'] = 10;//退回已结单待烹制完成阶段
				$data['delivery_time'] = 0;
			}
			if($order['order_status'] == 8){
				$data['transport_status'] = '指派单';
			}
			if($order['order_status'] == 9){
				$data['transport_status'] = '妥投异常返回中';
			}
			if($order['order_status'] == 10){
				$data['transport_status'] = '妥投异常返回完成';
			}
			if($order['order_status'] == 1000){
				$data['transport_status'] = '创建运单失败';
			}
		}
		if($mode==40){
			switch ((string)$data['state']) {
	            case '3': //已接单 - 骑手正赶往商家
					$dev = [
						'delivery_status' => 20,
						'linkman' => $data['driver_name'],
						'phone' => $data['driver_mobile']
					];
	                break;
	            case '4': //已到店 - 骑手已到店
					$dev = [
						'delivery_status' => 30
					];
	                break;
	            case '5': //已取件 - 骑手开始配送
					$dev = [
						'delivery_status' => 40
					];
	                break;
	            case '6';//到达目的地 - 骑手已送达
					$dev = [
						'delivery_status' => 50,
						'status' => 30
					];
	                break;
	            case '-1': //订单被取消
					$dev = [
						'delivery_status' => 10
					];
	                break;
	            default:
	            	return true;
	        }
		}
		$dev['delivery_time'] = time();
		return $this->delivery->save($dev);
	}

}
